package com.zhengsr.wanandroid.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhengsr.corelib.bean.ArticleCollectBean;
import com.zhengsr.corelib.bean.BaseResponse;
import com.zhengsr.corelib.bean.CollectBean;
import com.zhengsr.wanandroid.Constant;
import com.zhengsr.wanandroid.R;
import com.zhengsr.wanandroid.Utils;
import com.zhengsr.wanandroid.activity.LoginInActivity;
import com.zhengsr.wanandroid.mvp.base.BaseFragment;
import com.zhengsr.wanandroid.mvp.base.BasePresent;
import com.zhengsr.wanandroid.mvp.contract.ContractManager;
import com.zhengsr.wanandroid.mvp.present.KnowledgePresent;
import com.zhengsr.wanandroid.ui.main.adapter.HomeAdapter;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * Created by zhengshaorui
 * Time on 2019/2/26
 */

public class KnowledgeFragment extends BaseFragment implements ContractManager.IdetailKnowledge, 
        BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener,ContractManager.IAddOrCancelCollect {
    private static final String TAG = "KnowledgeFragment";
    private List<CollectBean> mData = new ArrayList<>();
    private HomeAdapter mAdapter;
    private KnowledgePresent mPresent;
    private int mCid = -1;
    private int mCurentPosition = -1 ;

    @BindView(R.id.recycler_smart)
    SmartRefreshLayout mSmartRefreshLayout;

    public static KnowledgeFragment newInstance(int id) {
        Bundle args = new Bundle();
        args.putInt(TAG,id);
        KnowledgeFragment fragment = new KnowledgeFragment();
        fragment.setArguments(args);
        return fragment;
    }
    
    @Override
    public int getLayoutId() {
        return R.layout.recycler_refresh_view;
    }

    @Override
    public BasePresent getPresent() {
        mPresent = KnowledgePresent.create(this);
        return mPresent;
    }

    @Override
    public void initView(View view) {
        initRecyclerView(view);

        initRefreshLayout();

    }

    @Override
    public void reload() {
        super.reload();
        if (mPresent != null){
            mPresent.getAllKnowTree();
        }
    }

    private void initRecyclerView(View view) {
        RecyclerView recyclerView = view.findViewById(R.id.recyclerview);
        LinearLayoutManager manager = new LinearLayoutManager(_mActivity,LinearLayoutManager.VERTICAL,false);
        recyclerView.setLayoutManager(manager);
        mAdapter = new HomeAdapter(R.layout.item_article_recy_layout, mData);
        recyclerView.setAdapter(mAdapter);

        mAdapter.setOnItemClickListener(this);
        mAdapter.setOnItemChildClickListener(this);
    }

    @Override
    protected void getLocalReceiver(Intent intent) {
        super.getLocalReceiver(intent);
        int id = intent.getIntExtra(Constant.KEY_ARTICLE_ID,-1);
        if (id != -1){
            CollectBean bean = mData.get(id);
            if (bean != null) {
                bean.setCollect(intent.getBooleanExtra(Constant.KEY_ARTICLE_COLLECT,false));
                mAdapter.setData(id, bean);
            }
        }
    }

    private void initRefreshLayout() {
        mSmartRefreshLayout.setEnableLoadMore(true);
        mSmartRefreshLayout.setEnableRefresh(true);
        mSmartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                if (mCid != -1) {
                    mPresent.refreshKnowledge(mCid);
                }else{
                    Toast.makeText(_mActivity, R.string.lastest_data, Toast.LENGTH_SHORT).show();
                }
                mSmartRefreshLayout.finishRefresh(1000);

            }
        });
        mSmartRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (mCid != -1) {
                    mPresent.loadMoreKnowledge(mCid);
                }else{
                    Toast.makeText(_mActivity, R.string.lastest_data, Toast.LENGTH_SHORT).show();
                }
                mSmartRefreshLayout.finishLoadMore(1000);
            }
        });
    }

    @Override
    public void onLazyInitView(@Nullable Bundle savedInstanceState) {
        super.onLazyInitView(savedInstanceState);
        Bundle bundle = getArguments();
        if (bundle == null){
            return;
        }
        mCid = bundle.getInt(TAG);
        if (mCid != -1) {
            mPresent.refreshKnowledge(mCid);
        }

    }



    @Override
    public void getDetailKnowledge(ArticleCollectBean bean,boolean isRefresh) {
        if (isRefresh){
            mAdapter.replaceData(bean.datas);
        }else {
            mAdapter.addData(bean.datas);
        }
    }

    @Override
    protected boolean showNormalView() {
        return false;
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        CollectBean bean = mData.get(position);
        Bundle bundle = new Bundle();
        bundle.putString("url",bean.getLink());
        bundle.putString("title",bean.getTitle());
        bundle.putInt("position",position);
        bundle.putInt("id",bean.getId());
        bundle.putInt("collect_state",bean.isCollect() ? 1:0);
        Utils.startAricleActivity(view,_mActivity,bundle);
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        if (view.getId() == R.id.item_search_pager_like_iv){
            if (!mPresent.getLoginStatus()){
                Toast.makeText(_mActivity, "请先登录", Toast.LENGTH_SHORT).show();
                startActivity(new Intent(_mActivity, LoginInActivity.class));
                return;
            }
            mCurentPosition = position;
            CollectBean bean = mData.get(position);
            if (bean != null){
                if (!bean.isCollect()) {
                    mPresent.addCollectArticle(bean.getChapterId());
                }else{
                    mPresent.cancelCollectArticle(bean.getChapterId());
                }
            }
        }

    }

    @Override
    public void addCollectArticleSuccess(BaseResponse<ArticleCollectBean> articleCollectBean) {
        if (mCurentPosition != -1){
            CollectBean bean = mData.get(mCurentPosition);
            bean.setCollect(true);
            mAdapter.setData(mCurentPosition,bean);
            Toast.makeText(_mActivity, R.string.add_article_success, Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void cancelCollectArticleSuccess(BaseResponse response) {
        if (mCurentPosition != -1){
            CollectBean bean = mData.get(mCurentPosition);
            bean.setCollect(false);
            mAdapter.setData(mCurentPosition,bean);
            Toast.makeText(_mActivity, R.string.cancel_article_success, Toast.LENGTH_SHORT).show();
        }
    }
}
